const orderModel = require("../../db/models")["order"];
const goodsModel = require("../../db/models")["goods"];
const cartModel = require("../../db/models")["cart"];
const bookOrderModel = require("../../db/models")["ordergoods"];
const responseCode = require("../../config/httpCode");
const { Op } = require("sequelize");
const router = require("koa-router")({
  prefix: "/api/order"
});

router.get("/", async ctx => {
  const id = ctx.$$user.id;
  const orders = await orderModel.findAll({
    where: { uid: id }
  });
  ctx.body = {
    code: 200,
    data: orders
  };
});

router.get("/all", async ctx => {
  const page = ctx.query.page || 1;
  const o = await orderModel.findAndCountAll();
  const orders = await orderModel.findAll({
    limit: 10,
    offset: (page - 1) * 10
  });
  ctx.body = {
    code: 200,
    data: {
      orders,
      total: o.count
    }
  };
});

// 获取
router.get("/:id", async ctx => {
  const id = ctx.params.id;
  const orders = await orderModel.findOne({
    where: { id },
    include: "goods"
  });
  ctx.body = {
    code: 200,
    data: orders
  };
});

// 增加
router.post("/", async ctx => {
  const id = ctx.$$user.id;
  const order = {
    place: ctx.request.body.place,
    name: ctx.request.body.name,
    phone: ctx.request.body.phone,
    total: ctx.request.body.total,
    status: 1
  };
  order.userId = id;
  // 添加至订单的商品
  const goods = ctx.request.body.goods;
  let goodsCondition = [];
  // 删除购物车的商品
  const cartCodition = goods.map(g => {
    goodsCondition.push({ id: g.id });
    return {
      bid: g.id,
      uid: id,
      count: g.count
    };
  });
  // 找到所有商品
  const goods_rtp = await goodsModel.findAll({
    where: {
      [Op.or]: goodsCondition
    }
  });
  // 商品加count
  goods_rtp.forEach(g => {
    goods.forEach(gg => {
      if (g.id === gg.id) {
        g.ordergoods = {
          count: gg.count || 1
        };
      }
    });
  });
  // 删除购物车的东西
  await cartModel.destroy({
    where: {
      [Op.or]: cartCodition
    }
  });
  // 创建订单
  const orders = await orderModel.create(order);
  await orders.addGoods(goods_rtp);
  ctx.body = {
    code: 200,
    data: orders
  };
});

// 修改
router.post("/:id", async ctx => {
  const id = ctx.params.id;
  const order = ctx.request.body;
  order.id = id;
  if (!order.status) {
    order.status = 2;
  }
  const orders = await orderModel.update(order, { where: { id } });
  ctx.body = {
    code: 200,
    data: orders
  };
});

router.delete("/:id", async ctx => {
  const id = ctx.params.id;
  const orders = await orderModel.destroy({ where: { id } });
  ctx.body = {
    code: 200,
    data: orders
  };
});
module.exports = router;
